/**
 * 
 */
package com.jeecms.wicool.action.product;

import static com.jeecms.common.page.SimplePage.cpn;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Function;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.jeecms.cms.entity.main.CmsGroup;
import com.jeecms.cms.entity.main.CmsUser;
import com.jeecms.cms.manager.main.CmsGroupMng;
import com.jeecms.cms.manager.main.CmsLogMng;
import com.jeecms.cms.web.CmsUtils;
import com.jeecms.cms.web.WebErrors;
import com.jeecms.common.page.Pagination;
import com.jeecms.common.web.CookieUtils;
import com.jeecms.common.web.ResponseUtils;
import com.jeecms.wicool.entity.image.ImageEntity;
import com.jeecms.wicool.entity.product.Product;
import com.jeecms.wicool.entity.product.ProductCate;
import com.jeecms.wicool.entity.product.ProductRelation;
import com.jeecms.wicool.entity.product.ProductSku;
import com.jeecms.wicool.entity.shops.ShopInfo;
import com.jeecms.wicool.entity.util.Dictionary2;
import com.jeecms.wicool.manager.image.ImageEntityManager;
import com.jeecms.wicool.manager.product.ProductCateMng;
import com.jeecms.wicool.manager.product.ProductMng;
import com.jeecms.wicool.manager.product.ProductRelationMng;
import com.jeecms.wicool.manager.product.ProductSkuMng;
import com.jeecms.wicool.manager.shops.WiShopInfoMng;
import com.jeecms.wicool.manager.util.DictionaryMng;

/**
 * @author spring
 * 
 */
@Controller
@RequestMapping("/vipProduct")
public class VIPProductAct {
	private static final Logger log = LoggerFactory.getLogger(ProductAct.class);

	@SuppressWarnings("unchecked")
	@RequestMapping("/v_list.do")
	public String list(String vipLevel,Integer productCateId, String productName,
			Integer pageNo, HttpServletRequest request, ModelMap model) {
		Pagination pagination = manager.getPageForVip(productCateId, productName,
				cpn(pageNo), CookieUtils.getPageSize(request),
				CmsUtils.getUser(request));
		List<Product> listProduct = (List<Product>) pagination.getList();
		List<Dictionary2> listDic = DicMng.getList("product_status");
		List<Dictionary2> listDic2 = DicMng.getList("yes_or_no");
		Map<String, String> map = new HashMap<String, String>();
		Map<String, String> map2 = new HashMap<String, String>();
		for (Dictionary2 d : listDic) {
			map.put(d.getDicCode().toString(), d.getDicName());
		}
		for (Dictionary2 d : listDic2) {
			map2.put(d.getDicCode().toString(), d.getDicName());
		}
		List<CmsGroup> listVipLevel = groupMng.getWeiXinList();
		
		for (Iterator<Product> iterator = listProduct.iterator(); iterator
				.hasNext();) {
			Product p = (Product) iterator.next();
			if (map.containsKey(p.getStatus().toString())) {
	            p.setStatusName(map.get(p.getStatus().toString()));
	        }
			if(StringUtils.isBlank(vipLevel)){
				if(StringUtils.isBlank(p.getUserLevel())){
					iterator.remove();
					continue;
				}
			}else{
				if (!p.getUserLevel().equals(vipLevel)) {
					iterator.remove();
					continue;
				}
			}
			
			for (CmsGroup cmsGroup : listVipLevel) {
				if(p.getUserLevel().equals(cmsGroup.getPriority().toString())){
					p.setUserLevelValue(cmsGroup.getName());
				}
			}
		}
		List<ProductCate> listProductCate = productCateMng.getListByCateLevel(
				null, CmsUtils.getUser(request));
		for (Iterator<ProductCate> iterator = listProductCate.iterator(); iterator
				.hasNext();) {
			ProductCate productCate = (ProductCate) iterator.next();
			if (productCate.getId() != 4) {// 过滤掉VIP商品
				iterator.remove();
			}
		}
		model.addAttribute("pagination", pagination);
		model.addAttribute("productCateId", productCateId);
		model.addAttribute("productName", productName);
		model.addAttribute("listProductCate", listProductCate);
		model.addAttribute("vipLevel", vipLevel);
		model.addAttribute("listVipLevel", listVipLevel);
		return "vipProduct/list_product";
	}

	@RequestMapping("/a_list.do")
	public void list(Integer productCateId, HttpServletResponse response) {
		List<Product> products = manager.getAll(productCateId);
		List<JSONObject> temp = Lists.transform(products,
				new Function<Product, JSONObject>() {
					@Override
					public JSONObject apply(Product product) {
						JSONObject json = new JSONObject();
						json.put("id", product.getId());
						json.put("name", product.getProductName());
						return json;
					}
				});
		ResponseUtils.renderJson(response, JSONObject.toJSONString(temp));
	}

	@RequestMapping("/v_toEditProduct.do")
	public String toEditProduct(Integer id, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		model.addAttribute("product_id", id);
		return "vipProduct/to_edit_product";
	}

	@RequestMapping("/v_edit.do")
	public String edit(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Product product = manager.findById(id);
		List<ImageEntity> imageList = imageManager.getAll(id,
				ImageEntity.INDEX_SCROLL_IMG);
		product.setImgList(ImmutableSet.copyOf(imageList));
		List<ShopInfo> listShop = shopMng.getAll(CmsUtils.getUser(request));
		List<ProductCate> listProductCate = productCateMng.getListByCateLevel(
				null, CmsUtils.getUser(request));
		for (Iterator<ProductCate> iterator = listProductCate.iterator(); iterator
				.hasNext();) {
			ProductCate productCate = (ProductCate) iterator.next();
			if (productCate.getId() != 4) {// 过滤掉VIP商品
				iterator.remove();
			}
		}
		
		List<CmsGroup> listVipLevel = groupMng.getWeiXinList();
		model.addAttribute("listVipLevel", listVipLevel);
		model.addAttribute("product", product);
		model.addAttribute("listShop", listShop);
		model.addAttribute("listProductCate", listProductCate);
		return "vipProduct/edit_product";
	}

	@RequestMapping("/v_edit_productRelation.do")
	public String editProductRelation(Integer productId, ProductRelation bean,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(productId, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Product product = manager.findById(productId);
		ProductRelation productRelation = product.getProductRelation();
		if (productRelation == null) {
			productRelation = new ProductRelation();
		}
		productRelation.setProduct(product);
		if (bean.getId() != null) {
			model.addAttribute("productRelation", bean);
		} else {
			model.addAttribute("productRelation", productRelation);
		}
		return "vipProduct/edit_productRelation";
	}

	@RequestMapping("/v_edit_productSpecification.do")
	public String editProductSpecification(Integer productId,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(productId, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		List<ProductSku> specifications = productSkuMng
				.getListProductSku(productId);
		Product product = manager.findById(productId);
		model.put("specifications", specifications);
		model.put("product", product);

		return "vipProduct/edit_productSpecification";
	}

	@RequestMapping("/v_edit_productSku.do")
	public String editProductSku(Integer productId, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateEdit(productId, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Product product = manager.findById(productId);
		List<ProductSku> listProductSku = productSkuMng
				.getListProductSku(productId);
		String skuCode;
		if (listProductSku != null && listProductSku.size() > 0) {
			List<Integer> listS = new ArrayList<Integer>();
			for (ProductSku ps : listProductSku) {
				ps.setProduct(product);
				listS.add(Integer.parseInt(ps.getSkuCode()));
			}
			skuCode = Collections.max(listS).toString();
		} else {
			skuCode = "0";
		}
		model.addAttribute("listProductSku", listProductSku);
		model.addAttribute("product", product);
		model.addAttribute("skuCode", skuCode);
		return "vipProduct/edit_productSku";
	}

	@RequestMapping("/o_save.do")
	public String save(Product bean, Integer shopId, Integer productCateId,
			String status, HttpServletRequest request, String[] imgUrls,
			Integer[] imgOrders, ModelMap model) {
		WebErrors errors = validateSave(bean, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		// 获取系统当前登陆人
		CmsUser user = CmsUtils.getUser(request);
		bean.setPublisher(user.getId());
		// 货号为空 自动生成
		if (bean.getItemNo() == null || bean.getItemNo().equals("")) {
			// 获取当前数据库中最大货号值+1
			Integer maxItemNo = manager.getMaxItemNo();
			bean.setItemNo(Integer.toString((maxItemNo + 1)));
		}
		bean = manager.save(bean, shopId, productCateId);

		if (null != imgUrls) {
			List<ImageEntity> entities = Lists.newLinkedList();
			for (int i = 0; i < imgUrls.length; i++) {
				ImageEntity entity = new ImageEntity();
				entity.setImageURL(imgUrls[i]);
				entity.setRelationId(bean.getId());
				entity.setOrder(imgOrders[i]);
				entity.setImgType(ImageEntity.INDEX_SCROLL_IMG);
				entities.add(entity);
			}
			for (ImageEntity entity : entities) {
				imageManager.save(entity);
			}
		}
		if (!Strings.isNullOrEmpty(bean.getImgUrl())) {
			ImageEntity entity = new ImageEntity(null, bean.getId(),
					bean.getImgUrl(), 0, ImageEntity.SMALL_IMG);
			imageManager.save(entity);
		}

		log.info("save Product id={}", bean.getId());
		cmsLogMng.operating(request, "Product.log.save", "id=" + bean.getId());
		return "redirect:v_list.do";
	}

	@RequestMapping("/o_update.do")
	public String update(Product bean, Integer shopId,
			final Integer productCateId, String status, Integer pageNo,
			String[] imgUrls, Integer[] imgOrders, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateUpdate(bean.getId(), request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		SimpleDateFormat simpleTime = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String dateTime = simpleTime.format(new Date());
		Timestamp t = Timestamp.valueOf(dateTime);

		bean.setUpdateTime(t);

		// 删除原有图片
		final Product product = manager.findById(bean.getId());
		List<ImageEntity> imgList = imageManager.getAll(bean.getId(),
				ImageEntity.INDEX_SCROLL_IMG);
		product.getImgList().clear();
		for (ImageEntity imageEntity : imgList) {
			imageManager.deleteById(imageEntity.getId());
		}
		List<ImageEntity> entities = Lists.newLinkedList();
		if (null != imgUrls) {
			for (int i = 0; i < imgUrls.length; i++) {
				ImageEntity entity = new ImageEntity();
				entity.setImageURL(imgUrls[i]);
				entity.setRelationId(product.getId());
				entity.setOrder(imgOrders[i]);
				entity.setImgType(ImageEntity.INDEX_SCROLL_IMG);
				entities.add(entity);
			}
			for (ImageEntity entity : entities) {
				imageManager.save(entity);
			}
		}
		bean = manager.update(bean, shopId, productCateId);
		bean.setImgList(Sets.newHashSet(entities));
		model.addAttribute("message", "global.success");
		log.info("update Product success. id={}", bean.getId());
		cmsLogMng
				.operating(request, "Product.log.update", "id=" + bean.getId());
		return edit(bean.getId(), request, model);
	}

	@RequestMapping("/o_updateProductRelation.do")
	public String updateProductRelation(ProductRelation bean,
			Integer productId, Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateUpdateForProductRelation(bean.getId(),
				request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Product product = manager.findById(productId);
		bean.setProduct(product);
		if (bean.getId() == null) { // 保存
			bean = productRelationMng.save(bean);
		} else { // 更新
			SimpleDateFormat simpleTime = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			String dateTime = simpleTime.format(new Date());
			Timestamp t = Timestamp.valueOf(dateTime);
			bean.setUpdateTime(t);
			bean = productRelationMng.update(bean);
		}
		model.addAttribute("message", "global.success");
		return editProductRelation(productId, bean, request, model);
	}

	@RequestMapping("/sku/a_list.do")
	public void getAllProductSku(Integer productId, HttpServletRequest request,
			HttpServletResponse response) {
		List<ProductSku> skuList = productSkuMng.getListProductSku(productId);
		List<JSONObject> pojos = Lists.transform(skuList,
				new Function<ProductSku, JSONObject>() {
					@Override
					public JSONObject apply(ProductSku sku) {
						JSONObject json = new JSONObject();
						json.put("skuName", sku.getSkuName());
						json.put("id", sku.getId());
						return json;
					}
				});
		ResponseUtils.renderJson(response, JSONObject.toJSONString(pojos));
	}

	@RequestMapping("/o_updateProductSku.do")
	public String updateProductSku(Integer productId, Integer[] psId,
			String[] skuCode, String[] skuName, BigDecimal[] price,
			BigDecimal[] priceMarket, Integer[] storeNum, BigDecimal[] freight,
			Integer pageNo, HttpServletRequest request, ModelMap model) {
		// WebErrors errors = validateUpdateForProductRelation(bean.getId(),
		// request);
		// if (errors.hasErrors()) {
		// return errors.showErrorPage(model);
		// }
		Product product = manager.findById(productId);
		List<ProductSku> listProductSku = getListProductSku(product, psId,
				skuCode, skuName, price, priceMarket, storeNum, freight);
		productSkuMng.updateList(listProductSku, productId);
		model.addAttribute("message", "global.success");
		return editProductSku(productId, request, model);
	}

	public List<ProductSku> getListProductSku(Product product, Integer[] psId,
			String[] skuCode, String[] skuName, BigDecimal[] price,
			BigDecimal[] priceMarket, Integer[] storeNum, BigDecimal[] freight) {
		List<ProductSku> list = new ArrayList<ProductSku>();
		ProductSku ps;
		for (int i = 0; i < skuCode.length; i++) {
			ps = new ProductSku();
			if (psId != null && psId[i] != null) {
				ps.setId(psId[i]);
			}
			ps.setSkuCode(skuCode[i]);
			ps.setSkuName(skuName[i]);
			ps.setPrice(price[i]);
			ps.setPriceMarket(priceMarket[i]);
			ps.setFreight(freight[i]);
			ps.setStoreNum(storeNum[i]);
			ps.setProduct(product);
			list.add(ps);
		}
		return list;
	}

	/**
	 * 添加商品类型
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("/v_add.do")
	public String add(ModelMap model, HttpServletRequest request) {
		Product product = new Product();
		List<ShopInfo> listShop = shopMng.getAll(CmsUtils.getUser(request));
		List<ProductCate> listProductCate = productCateMng.getListByCateLevel(
				null, CmsUtils.getUser(request));
		for (Iterator<ProductCate> iterator = listProductCate.iterator(); iterator
				.hasNext();) {
			ProductCate productCate = (ProductCate) iterator.next();
			if (productCate.getId() != 4) {// 过滤掉VIP商品
				iterator.remove();
			}
		}
		
		List<CmsGroup> listVipLevel = groupMng.getWeiXinList();
		model.addAttribute("listVipLevel", listVipLevel);
		
		List<Dictionary2> listDic = DicMng.getList("product_status");
		model.addAttribute("product", product);
		model.addAttribute("listShop", listShop);
		model.addAttribute("listProductCate", listProductCate);
		model.addAttribute("listDic", listDic);
		return "vipProduct/add_product";
	}

	@RequestMapping("/o_delete.do")
	public String delete(Integer[] ids, String vipLevel, Integer productCateId,
			String productName, Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateDelete(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Product[] beans = manager.deleteByIds(ids);
		for (Product bean : beans) {
			log.info("delete Product id={}", bean.getId());
			cmsLogMng.operating(request, "Product.log.delete",
					"id=" + bean.getId() + ";name=" + bean.getProductName());
			List<ImageEntity> entities = imageManager.getAll(bean.getId(),
					ImageEntity.SMALL_IMG);
			for (ImageEntity entity : entities) {
				imageManager.deleteById(entity.getId());
			}
		}
		return list(vipLevel,productCateId, productName, pageNo, request, model);
	}

	private WebErrors validateSave(Product bean, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		return errors;
	}

	private WebErrors validateEdit(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		return errors;
	}

	private WebErrors validateUpdate(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		// TODO 验证是否为管理员，管理员不允许修改。
		return errors;
	}

	private WebErrors validateUpdateForProductRelation(Integer id,
			HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (vldExistForProductRelation(id, errors)) {
			return errors;
		}
		// TODO 验证是否为管理员，管理员不允许修改。
		return errors;
	}

	private WebErrors validateDelete(Integer[] ids, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		errors.ifEmpty(ids, "ids");
		for (Integer id : ids) {
			vldExist(id, errors);
		}
		return errors;
	}

	private boolean vldExist(Integer id, WebErrors errors) {
		if (errors.ifNull(id, "id")) {
			return true;
		}
		Product entity = manager.findById(id);
		if (errors.ifNotExist(entity, Product.class, id)) {
			return true;
		}
		return false;
	}

	private boolean vldExistForProductRelation(Integer id, WebErrors errors) {
		if (errors.ifNull(id, "id")) {
			return true;
		}
		ProductRelation entity = productRelationMng.findById(id);
		if (errors.ifNotExist(entity, ProductRelation.class, id)) {
			return true;
		}
		return false;
	}

	@Autowired
	private ProductMng manager;
	@Autowired
	private ProductCateMng productCateMng;
	@Autowired
	private WiShopInfoMng shopMng;
	@Autowired
	private CmsLogMng cmsLogMng;
	@Autowired
	private DictionaryMng DicMng;
	@Autowired
	private ProductRelationMng productRelationMng;
	@Autowired
	private ProductSkuMng productSkuMng;

	@Autowired
	private ImageEntityManager imageManager;
	
	@Autowired
	private CmsGroupMng groupMng;
}
